// 导入数据库操作模块
const { mysql } = require("../../db");
const moment = require("moment");
const { filesURL } = require("../../../config");

// 获取所有角色
// exports.Info = (req, res) => {
//     const sqlStr1 = `SELECT * FROM ${table} where is_delete = 0`
//     const sqlStr2 = `
//         SELECT roles.*,anime.cover,anime.nickname AS production FROM roles
//         JOIN anime_roles ON roles.id = anime_roles.roles_id
//         JOIN anime ON anime_roles.anime_id = anime.id
//         WHERE roles.is_delete = 0;
//     `;

//     mysql.query(sqlStr1, (err, results1) => {
//         if (err) return res.cc(err)
//         if (results1.length === 0) return res.cc("暂无角色信息!");

//         mysql.query(sqlStr2, (err, results2) => {
//             if (err) return res.cc(err);

//             // 剔除results1中和results2中id相同项并保留results2的
//             const idSet = new Set(results2.map(item => item.id));
//             const resultsDict = {};
//             for (const item of results2) {
//                 resultsDict[item.id] = item;
//             }

//             const results = results1.filter(item => !idSet.has(item.id)).concat(Object.values(resultsDict));

//             const data = results.map(o => ({
//                 ...o,
//                 avatar: o.avatar ? `${filesURL}/images/roles/${o.avatar}` : null,
//                 cover: o.cover ? `${filesURL}/images/cover/${o.cover}` : null,
//                 age: o.age === 0 ? "?" : o.age,
//                 production: o.production ? '《' + o.production + '》' : null,
//                 gender: o.gender === 0 ? '男' :
//                     o.gender === 1 ? '女' : '未知',
//                 types: o.types === 0 ? '动漫' :
//                     o.types === 1 ? '漫画' :
//                         o.types === 2 ? 'Galgame' : '小说',
//                 create: moment(o.create).format('YYYY-MM-DD HH:mm:ss')
//             }));

//             res.json({
//                 status: 0,
//                 message: "获取角色信息成功!",
//                 data
//             })
//         })
//     });
// };

const formatData = (results) => {
	try {
		const data = results.map(o => ({
			...o,
			avatar: o.avatar ? `${filesURL}/images/roles/${o.avatar}` : null,
			cover: o.cover ? `${filesURL}/images/cover/${o.cover}` : null,
			age: o.age === 0 ? "?" : o.age,
			production: o.production ? `《${o.production}》` : null,
			gender: ["男", "女", "未知"][o.gender] || "未知",
			types: ["番剧", "漫画", "Galgame", "小说"][o.types] || "其他",
			create: moment(o.create).format("YYYY-MM-DD HH:mm:ss")
		}));
		return data;
	} catch (err) {
		throw err;
	}
};

exports.Info = async (req, res, table) => {
	try {
		const sqlStr = `SELECT * FROM ${table} WHERE is_delete = 0`;
		const [results] = await mysql.query(sqlStr);
		if (results.length === 0) return res.error("获取失败，无角色信息！");
		const data = formatData(results);
		return res.success(data);
	} catch (err) {
		return res.error(err);
	}
};

exports.Add = async (req, res, table) => {
	try {
		const { rolename, c_name, nickname, race, age, gender, intro, types } = req.body;
		const data = { rolename, c_name, nickname, race, age, gender, intro, types, creator: req.user.id };
		const sqlStr = `INSERT INTO ${table} SET ?`;
		const [results] = await mysql.query(sqlStr, data);
		if (results.affectedRows !== 1) return res.error("新增角色信息失败！");
		return res.success("新增角色信息成功!");
	} catch (err) {
		return res.error(err);
	}
};

exports.Update = async (req, res, table) => {
	try {
		const { rolename, c_name, nickname, race, age, gender, intro, types, id } = req.body;
		const data = [rolename, c_name, nickname, race, age, gender, intro, types, id];
		const sqlStr = `UPDATE ${table} SET rolename=?,c_name=?,nickname=?,race=?,age=?,gender=?,intro=?,types=? WHERE id = ?`;

		const [results] = await mysql.query(sqlStr, data);
		if (results.affectedRows !== 1) {
			return res.error("更新信息失败！");
		}

		return res.success("更新信息成功!");
	} catch (err) {
		return res.error(err);
	}
};

exports.Search = async (req, res, table) => {
	try {
		const params = req.params.value;
		const sqlStr = `SELECT * From ${table} WHERE (rolename LIKE ? OR c_name LIKE ? OR nickname LIKE ? OR intro LIKE ? OR race LIKE ? OR age LIKE ? OR gender LIKE ? OR types LIKE ?) AND is_delete = 0`;
		const SeletePattern = `%${params}%`;
		const values = Array(8).fill(SeletePattern);
		const [results] = await mysql.query(sqlStr, values);
		if (results.length === 0) return res.error("该角色信息不存在！");
		const data = formatData(results);
		return res.success(data);
	} catch (err) {
		return res.error(err);
	}
};
